package com.chenxi.common.service;

import com.chenxi.common.mapper.BaseMapper;
import com.chenxi.util.PageData;
import com.chenxi.util.PageForm;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.ParameterizedType;
import java.util.Arrays;

/**
 * ${DESCRIPTION}
 *
 * @author Hu Xiaolong
 * @version V0.1
 * @create 2017/12/22
 */
public class BaseServiceImpl<T> implements IBaseService<T>{

    private BaseMapper<T> baseMapper;

    public BaseServiceImpl() {

    }

    public BaseServiceImpl(BaseMapper<T> baseMapper) {
        this.baseMapper = baseMapper;
    }

    public BaseMapper<T> getBaseMapper() {
        return baseMapper;
    }

    @Override
    public T get(Long objId) {
        return baseMapper.selectByPrimaryKey(objId);
    }

    @Override
    public int save(T t) {
        return baseMapper.insert(t);
    }

    @Override
    public int update(T t) {
        return baseMapper.updateByPrimaryKey(t);
    }

    @Override
    public PageData<T> page(PageForm pageForm) {
        PageData<T> pageData = new PageData();
        PageInfo<T> pageInfo = PageHelper.startPage(pageForm.getPage(),pageForm.getPageSize()).doSelectPageInfo(()->{

            Example example = new Example((Class <T>)((ParameterizedType)(this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]);
            if (pageForm.getParams()!=null && !pageForm.getParams().isEmpty()) {
                Example.Criteria criteria = example.createCriteria();
                pageForm.getParams().forEach((k,v)->criteria.andCondition(k,v));
            }
            if (pageForm.getOrder()!= null) {
                Example.OrderBy order = example.orderBy(pageForm.getOrder());
                if (pageForm.getSort()!=null&&"desc".equals(pageForm.getSort())) {
                    order.desc();
                }else {
                    order.asc();
                }
            }
            baseMapper.selectByExample(example);
        });
        pageData.setDraw(pageForm.getDraw());
        pageData.setRecordsTotal(pageInfo.getTotal());
        pageData.setRecordsFiltered(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        return pageData;
    }

    @Override
    public void delete(Long objId) {
        baseMapper.deleteByPrimaryKey(objId);
    }

    @Override
    public int batchSave(T... t) {
        return baseMapper.insertList(Arrays.asList(t));
    }

    @Override
    public void batchUpdate(T... t) {

    }

    @Override
    public void batchDelete(Long... objId) {

    }
}
